package com.nyist.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义 Ribbon 轮询算法
 */
@Component
public class Mylb implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private final int getAndIncrement(){
        int current;
        int next;
        do {
            current=this.atomicInteger.get();
            next = current >= 2147483647 ? 0 :current + 1;   //int 最大值 2147483647
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("*******第几次访问呢，次数next："+next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstanceList) {
        int index=getAndIncrement() % serviceInstanceList.size();
        return serviceInstanceList.get(index);
    }
}
